<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>只因你太美</title>
  <link rel="stylesheet" href="index.css">
</head>

<body>
  <div class="content">
    <div class="chicken-wrapper">
      <div class="video-wrapper">
        <video src="./asset/because_you_are_so_beautiful.mp4" muted="true" id="video" autoplay loop oncanplay="init()"
          width="100%" height="100%" crossOrigin="anonymous"></video>
      </div>
      <canvas id="cvs"></canvas>
      <canvas id="cvs2" onclick="video.play()" loop>
      </canvas>
      <div class="card">
        <span class="card-text">演唱</span>
        <img class="card-img" src="./asset/shutUp.png" alt="">
      </div>

    </div>
    
  </div>


</body>
<script>
  // 解决音频跨域问题

  //音频控制--静音和演唱
  let mutedFlag = false
  document.querySelector('.card').onclick = () => {
    if (mutedFlag) {
      video.muted = true
      mutedFlag = false
      document.querySelector('.card-text').innerHTML = '演唱'
      document.querySelector('.card-img').src = './asset/shutUp.png'
    }
    else {
      video.muted = false
      mutedFlag = true
      document.querySelector('.card-text').innerHTML = '闭嘴'
      document.querySelector('.card-img').src = './asset/singing.png'
    }
  }
  

  //左侧只因你太美字符串动画
  const init = () => {
    const ctx = cvs.getContext('2d')
    const ctx2 = cvs2.getContext('2d')
    //该方法返回一个对象，该对象提供了用于在画布上绘图的方法和属性
    video.crossOrigin = '';
    //offsetHeight = height + padding + border
    //宽高和video进行同步
    //cvs1获取video，cvs2获取cvs1的像素信息
    cvs.height = cvs2.height = video.offsetHeight
    cvs.width = cvs2.width = video.offsetWidth
    const playVideo = () => {
      requestAnimationFrame(playVideo)
      // playVideo回调函数 重绘之前更新动画帧
      const { width, height } = cvs
      //cvs1获取video
      ctx.drawImage(video, 0, 0, width, height)
      //cvs2获取cvs1的像素信息
      const data = ctx.getImageData(0, 0, width, height).data
      //每次渲染之前cvs2清空
      ctx2.clearRect(0, 0, width, height)
      //bl稀释比例
      const bl = 8
      //字体样式
      ctx.font = '12px serif'
      //rgba格式有4个参数，故i需要+=4以获取4个参数
      for (let i = 0; i < data.length; i += 4 * bl) {
        const x = parseInt((i + 1) % (width * 4) / 4)
        const y = parseInt(i / (width * 4))
        //rgba转灰度
        if (x % bl === 0 && y % bl === 0) {
          //修改const g = parseInt((data[i] + data[i+1] + data[i+2]) / 1.5)中的1.5可以改变清晰度
          const g = parseInt((data[i] + data[i + 1] + data[i + 2]) / 1.5)
          ctx2.fillStyle = `rgba(${g}, ${g}, ${g}, ${data[i + 3]})`
          //修改ctx2.fillText('6', x, y)中的6可以改变显示的字符
          ctx2.fillText('6', x, y)
        }
      }
    }
    playVideo()
  }

</script>


</html>